import { defineStore } from 'pinia'
import { ref, watchEffect } from 'vue'

export const useBreadcrumbStore = defineStore('breadcrumb', () => {
    const list = ref<any[]>([])

    // 初始化时从 localStorage 读取
    const initFromStorage = () => {
        try {
            const data = localStorage.getItem('breadcrumbs')
            list.value = data ? JSON.parse(data) : []
        } catch (e) {
            console.error('面包屑初始化失败', e)
            list.value = []
        }
    }

    // 更新方法（供子页面调用）
    const updateBreadcrumbs = (newList: any[]) => {
        list.value = newList
        localStorage.setItem('breadcrumbs', JSON.stringify(newList))
    }

    // 自动监听当前页的修改
    watchEffect(() => {
        let v = list.value;
        if (v.length > 0) {
            let _v = JSON.stringify(v);
            let __breadcrumbs = localStorage.getItem('breadcrumbs')
            if (__breadcrumbs != _v) {
                localStorage.setItem('breadcrumbs', _v);
            }
        }
    })

    return {
        list,
        initFromStorage,
        updateBreadcrumbs
    }
})